from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.utils import timezone
import logging
from django.urls import reverse
from core.models import Chapter, Subject, TeacherSubjectAssignment
from core.forms.chapter_form import ChapterForm
from core.utils import log_operation

# 配置日志
logger = logging.getLogger(__name__)

@login_required
def chapter_create(request):
    """创建新章节"""
    # 获取用户有权限的学科
    user_subjects = TeacherSubjectAssignment.objects.filter(teacher=request.user).values_list('subject_id', flat=True)
    
    if request.method == 'POST':
        form = ChapterForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            # 验证权限
            if subject.id not in user_subjects:
                form.add_error('subject', '无权限操作此学科')
            else:
                # 检查章节名称是否已存在
                if Chapter.objects.filter(subject=subject, name=form.cleaned_data['name']).exists():
                    form.add_error('name', '该学科下已存在同名章节')
                else:
                    with transaction.atomic():
                        chapter = form.save()
                    log_operation(
                        user=request.user,
                        operation_type='create',
                        content_type='Chapter',
                        object_id=chapter.id,
                        object_name=chapter.name,
                        request=request,
                        details=f'创建章节: {chapter.name}, 学科ID: {chapter.subject_id}'
                    )
                    return redirect('core:subject_chapter_knowledge', subject_id=chapter.subject_id)
    else:
        # 初始化表单，只显示用户有权限的学科
        form = ChapterForm()
        form.fields['subject'].queryset = Subject.objects.filter(id__in=user_subjects)
    
    subject_id = request.GET.get('subject_id')
    if subject_id and subject_id.isdigit():
        subject_id = int(subject_id)
        if subject_id not in user_subjects:
            subject_id = None
    else:
        subject_id = None

    # Set default subject if available
    if subject_id is None and user_subjects:
        subject_id = user_subjects[0]

    return render(request, 'chapter/chapter_form.html', {
        'form': form,
        'title': '创建章节',
        'subject_id': subject_id
    })

@login_required
def chapter_list(request):
    """显示章节列表"""
    # 获取用户有权限的学科
    teacher_subjects = TeacherSubjectAssignment.objects.filter(teacher=request.user).values_list('subject_id', flat=True)
    
    # 构建查询集
    queryset = Chapter.objects.filter(subject_id__in=teacher_subjects).order_by('order')
    
    return render(request, 'chapter/chapter_list.html', {'chapters': queryset})

@login_required
def chapter_update(request, pk):
    """更新章节信息"""
    chapter = get_object_or_404(Chapter, pk=pk)
    
    # 检查用户是否有权限操作此章节所属的学科
    if not TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=chapter.subject_id
    ).exists():
        return render(request, 'chapter/permission_denied.html', status=403)
    
    if request.method == 'POST':
        form = ChapterForm(request.POST, instance=chapter)
        if form.is_valid():
            # 检查章节名称是否已存在（排除当前章节）
            if Chapter.objects.filter(
                subject_id=chapter.subject_id,
                name=form.cleaned_data['name']
            ).exclude(id=pk).exists():
                form.add_error('name', '该学科下已存在同名章节')
            else:
                with transaction.atomic():
                    chapter = form.save()
                log_operation(
                    user=request.user,
                    operation_type='update',
                    content_type='Chapter',
                    object_id=chapter.id,
                    object_name=chapter.name,
                    request=request,
                    details=f'更新章节: {chapter.name}, 学科ID: {chapter.subject_id}'
                )
                return redirect('core:subject_chapter_knowledge', subject_id=chapter.subject_id)
    else:
        form = ChapterForm(instance=chapter)
        # 限制学科选择为当前章节的学科
        form.fields['subject'].queryset = Subject.objects.filter(id=chapter.subject_id)
        form.fields['subject'].disabled = True  # 不允许更改学科
    return render(request, 'chapter/chapter_form.html', {'form': form, 'title': '更新章节', 'subject_id': chapter.subject_id})


@login_required
def chapter_delete(request, pk):
    """删除章节"""
    chapter = get_object_or_404(Chapter, pk=pk)
    
    # 检查用户是否有权限操作此章节所属的学科
    if not TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=chapter.subject_id
    ).exists():
        return render(request, 'chapter/permission_denied.html', status=403)
    
    # 检查是否有子知识点
    if chapter.knowledge_points.exists():
        return render(request, 'chapter/chapter_error.html', {
            'message': '无法删除，该章节下包含知识点'
        })
    
    if request.method == 'POST':
                with transaction.atomic():
                    chapter_name = chapter.name
                    subject_id = chapter.subject_id
                    chapter.delete()
                log_operation(
                    user=request.user,
                    operation_type='delete',
                    content_type='Chapter',
                    object_id=pk,
                    object_name=chapter_name,
                    request=request,
                    details=f'删除章节: {chapter_name}, 学科ID: {subject_id}'
                )
                return redirect('core:subject_chapter_knowledge', subject_id=subject_id)
    
    return render(request, 'chapter/chapter_confirm_delete.html', {'chapter': chapter})